<template>
  <div>
    <BasicTable @register="registerTable">
      <template #toolbar>
        <a-button type="primary" @click="handleCreate"> 新增 </a-button>
      </template>

      <template #bodyCell="{ column, record }">
        <template v-if="column.key === 'filename'">
          <Upload
            :maxCount="1"
            :before-upload="(file) => handleBeforeUploadFilename(file, { key: column.key, record })"
            accept="image/*"
          >
            <a-button type="primary">
              <upload-outlined />
              上传
            </a-button>
          </Upload>
        </template>
        <template v-if="column.key === 'roleNames'">
          <SelectRoleInput
            :roleCodes="record.roleCodes"
            v-model:value="record.roleNames"
            @change="(val, node) => handleRoleNames(val, node, record)"
          />
        </template>
        <template v-if="column.key === 'userRealNames'">
          <SelectUserInput
            :hadUsers="record['hadUsers']"
            v-model:value="record.userRealNames"
            @change="(val, node) => handleUserRealNames(val, node, record)"
          />
        </template>
        <!-- <template v-if="column.key === 'imgPath'">
          <a @click="handleViewImg(record)" v-if="!!record.imgPath">查看</a>
        </template> -->
      </template>
      <template #action="{ record }">
        <TableAction
          :actions="[
            {
              icon: 'ant-design:save-outlined',
              tooltip: '保存',
              onClick: handleSave.bind(null, record),
              ifShow: !record.id,
            },
            {
              icon: 'clarity:note-edit-line',
              tooltip: '修改',
              onClick: handleEdit.bind(null, record),
              ifShow: !!record.id,
            },
            {
              icon: 'ant-design:delete-outlined',
              color: 'error',
              tooltip: '删除',
              popConfirm: {
                title: '是否确认删除',
                confirm: handleDelete.bind(null, record),
              },
              ifShow: !!record.id,
            },
            {
              icon: 'clarity:info-standard-line',
              tooltip: '日志',
              onClick: handleView.bind(null, record),
              ifShow: !!record.id,
            },
          ]"
        />
      </template>
      <template #footer>
        <div class="pt-2 pb-2">
          注意：
          <div>1、如果编辑时上传了图片，则会替换原来的图片</div>
          <div>2、意见输入框中使用的是私章，即只根据授权用户取私章</div>
          <div> 3、图片签名框宏控件、Office宏控件中签章则根据授权角色及授权用户获取印章</div>
        </div>
      </template>
    </BasicTable>
    <ShowImgModal @register="registerShowImgModal" />
    <SealListDrawer @register="registerDrawer" @success="handleSuccess" />
  </div>
</template>
<script lang="ts">
  import { defineComponent, onMounted, ref, h } from 'vue';
  import { BasicTable, useTable, TableAction } from '/@/components/Table';
  import {
    getStampList,
    getStampDel,
    getStampCreate,
    getStampUpdate,
  } from '/@/api/flowManage/flowManage';
  import { columns, searchFormSchema } from './sealList.data';
  import { Upload } from 'ant-design-vue';
  import { useMessage } from '/@/hooks/web/useMessage';
  import { useModal } from '/@/components/Modal';
  import ShowImgModal from './ShowImgModal.vue';
  import { useDrawer } from '/@/components/Drawer';
  import SealListDrawer from './SealListDrawer.vue';
  import { SelectRoleInput, SelectUserInput } from '/@/components/CustomComp';
  import { isArray } from '/@/utils/is';

  export default defineComponent({
    name: 'SealList',
    components: {
      BasicTable,
      TableAction,
      Upload,
      ShowImgModal,
      SealListDrawer,
      SelectRoleInput,
      SelectUserInput,
    },
    props: {
      tableName: {
        type: String,
        default: '',
      },
    },
    emits: ['handle-view'],
    setup(props, { emit }) {
      const { createMessage } = useMessage();
      const [registerShowImgModal, { openModal }] = useModal();
      const [registerTable, { reload, setProps, redoHeight, getDataSource }] = useTable({
        title: props.tableName,
        api: getStampList,
        columns,
        formConfig: {
          labelWidth: 40,
          schemas: searchFormSchema,
          autoSubmitOnEnter: true,
        },
        searchInfo: {
          op: 'search',
          by: 'name',
        }, //额外的参数
        useSearchForm: true,
        showTableSetting: false,
        bordered: true,
        indexColumnProps: { width: 50 },
        showIndexColumn: true,
        canResize: false,
        // beforeFetch: (info) => {
        //   let newInfo = info;
        //   if (newInfo.dates && newInfo.dates.length > 0) {
        //     newInfo.fromDate = newInfo.dates[0];
        //     newInfo.toDate = newInfo.dates[1];
        //     delete newInfo.dates;
        //   }
        //   return newInfo;
        // },
        afterFetch: (data) => {
          if (isArray(data)) {
            data.forEach((record) => {
              record['hadUsers'] = [];
              if (record['userRealNames']) {
                const realNames = record['userRealNames'].split(',');
                const userNames = record['userNames'].split(',');
                realNames.forEach((item, index) => {
                  record['hadUsers'].push({
                    key: userNames[index],
                    name: userNames[index],
                    title: item,
                    realName: item,
                  });
                });
              }
            });
          }
          return data;
        },
        actionColumn: {
          width: 80,
          title: '操作',
          dataIndex: 'action',
          slots: { customRender: 'action' },
        },
      });

      const [registerDrawer, { openDrawer }] = useDrawer();
      function handleCreate() {
        openDrawer(true, {
          isUpdate: false,
        });
        // let data = getDataSource();
        // data.push({ kind: 'default', pwd: '111111' });
      }
      function handleSuccess() {
        reload();
      }

      //新增
      const handleSave = async (record) => {
        if (!record['title']) {
          return createMessage.warning('名称不能为空');
        }
        if (!record['filename']) {
          return createMessage.warning('图片不能为空');
        }
        try {
          let Files = new FormData();
          for (let v in record) {
            Files.append(v, record[v]);
          }
          setProps({ loading: true });
          await getStampCreate(Files);
          createMessage.success('操作成功');
          reload();
        } finally {
          setProps({ loading: false });
        }
      };
      //修改
      const handleEdit = async (record) => {
        if (!record['title']) {
          return createMessage.warning('名称不能为空');
        }
        try {
          setProps({ loading: true });

          let Files = new FormData();
          for (let v in record) {
            Files.append(v, record[v]);
          }
          await getStampUpdate(Files);
          createMessage.success('操作成功');
          reload();
        } finally {
          setProps({ loading: false });
        }
      };
      //删除
      const handleDelete = async (record) => {
        try {
          setProps({ loading: true });
          await getStampDel({ id: record.id });
          createMessage.success('操作成功');
          reload();
        } finally {
          setProps({ loading: false });
        }
      };
      //日志
      const handleView = (record) => {
        emit('handle-view', record);
      };

      const handleBeforeUploadFilename = (file, { key, record }) => {
        record[key] = file;
        return false;
      };

      const handleViewImg = async (record) => {
        if (!record.imgPath) {
          return createMessage.warning('无图片');
        }
        openModal(true, {
          path: record.imgPath,
        });
      };

      const handleRoleNames = (val, node, record) => {
        const { dataRef } = node;
        record.roleNames = val;
        record.roleCodes = dataRef['codes'];
      };

      const handleUserRealNames = (val, node, record) => {
        const { dataRef, selectUsers } = node;
        record.userNames = dataRef.userNames;
        record.userRealNames = val;
        record.hadUsers = selectUsers;
      };

      return {
        registerTable,
        handleCreate,
        handleSave,
        handleEdit,
        handleDelete,
        handleView,
        handleBeforeUploadFilename,
        handleViewImg,
        registerShowImgModal,
        registerDrawer,
        handleSuccess,
        handleRoleNames,
        handleUserRealNames,
      };
    },
  });
</script>
